<template>
  <div class="jsa-template-table-form">
    <div class="form-header">
      <div class="header-row">
        <div class="step-header">
          <h4>基本工作步骤</h4>
        </div>
        <div class="hazard-header">
          <h4>潜在的危险</h4>
        </div>
        <div class="control-header">
          <h4>风险控制措施</h4>
        </div>
      </div>
    </div>
    
    <div class="form-body">
      <div
        v-for="(step, stepIndex) in formData.workSteps || []"
        :key="stepIndex"
        class="form-row"
      >
        <!-- 工作步骤列 -->
        <div class="step-cell">
          <div class="step-number">{{ stepIndex + 1 }}</div>
          <div class="step-content">
            <el-input
              v-model="step.stepName"
              type="textarea"
              :rows="1"
              placeholder="请输入工作步骤"
              class="step-name-input"
            />
            <div class="step-actions">
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="removeStep(stepIndex)"
                :disabled="formData.workSteps.length <= 1"
              >
                删除步骤
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 潜在危险列 -->
        <div class="hazard-cell">
          <div
            v-for="(hazard, hazardIndex) in getStepHazards(stepIndex)"
            :key="hazardIndex"
            class="hazard-item"
          >
            <div class="hazard-number">{{ hazardIndex + 1 }}</div>
            <div class="hazard-content">
              <el-input
                v-model="hazard.hazardName"
                type="textarea"
                :rows="1"
                placeholder="请输入潜在危险"
                class="hazard-name-input"
              />
              <div class="hazard-actions">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  @click="removeHazard(stepIndex, hazardIndex)"
                >
                  删除危险
                </el-button>
              </div>
            </div>
          </div>
          <div class="add-hazard">
            <el-button
              type="primary"
              size="small"
              :icon="Plus"
              @click="addHazardToStep(stepIndex)"
            >
              添加危险
            </el-button>
          </div>
        </div>
        
        <!-- 控制措施列 -->
        <div class="control-cell">
          <!-- 为每个危险显示对应的控制措施 -->
          <div
            v-for="(hazard, hazardIndex) in getStepHazards(stepIndex)"
            :key="`hazard-${hazardIndex}`"
            class="hazard-control-group"
          >
            <div class="hazard-title">
              <span class="hazard-label">危险 {{ hazardIndex + 1 }} 的控制措施：</span>
            </div>
            
            <div
              v-for="(control, controlIndex) in getControlsForHazard(hazard)"
              :key="`control-${controlIndex}`"
              class="control-item"
            >
              <div class="control-number">{{ controlIndex + 1 }}</div>
              <div class="control-content">
                <el-input
                  v-model="control.measureName"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入控制措施"
                  class="control-name-input"
                />
                <div class="control-actions">
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    @click="removeControlFromHazard(hazard, controlIndex)"
                  >
                    删除措施
                  </el-button>
                </div>
              </div>
            </div>
            
            <div class="add-control-to-hazard">
              <el-button
                type="success"
                size="small"
                :icon="Plus"
                @click="addControlToHazard(hazard)"
              >
                为此危险添加措施
              </el-button>
            </div>
          </div>
          
          <!-- 如果没有危险，显示提示 -->
          <div v-if="getStepHazards(stepIndex).length === 0" class="no-hazards">
            <el-text type="info">请先添加潜在危险</el-text>
          </div>
        </div>
      </div>
    </div>
    
    <div class="form-footer">
      <el-button type="primary" :icon="Plus" @click="addStep">
        添加工作步骤
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import type { JSATemplateForm, JSAWorkStep, JSAHazard, JSAControlMeasure } from '@/types'


interface Props {
  modelValue: JSATemplateForm
}

interface Emits {
  (e: 'update:modelValue', value: JSATemplateForm): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单数据
const formData = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听危险名称变化，同步更新关联关系
watch(() => formData.value.hazards, (newHazards, oldHazards) => {
  if (!newHazards || !oldHazards) return
  
  newHazards.forEach((newHazard, index) => {
    const oldHazard = oldHazards[index]
    if (oldHazard && newHazard.hazardName !== oldHazard.hazardName) {
      // 更新关联关系中的hazardName
      formData.value.workStepHazards?.forEach(relation => {
        if (relation.hazardName === oldHazard.tempId || relation.hazardName === oldHazard.hazardName) {
          relation.hazardName = newHazard.hazardName
        }
      })
      
      // 更新危险-控制措施关联关系
      formData.value.hazardControls?.forEach(relation => {
        if (relation.hazardName === oldHazard.tempId || relation.hazardName === oldHazard.hazardName) {
          relation.hazardName = newHazard.hazardName
        }
      })
      
      // 清除临时ID
      if (newHazard.tempId) {
        delete newHazard.tempId
      }
    }
  })
}, { deep: true })

// 获取工作步骤相关的危险
const getStepHazards = (stepIndex: number) => {
  const step = formData.value.workSteps?.[stepIndex]
  if (!step) return []
  
  return (formData.value.hazards || []).filter(hazard => {
    return (formData.value.workStepHazards || []).some(relation => 
      relation.workStepSequence === stepIndex + 1 && 
      (relation.hazardName === hazard.hazardName || relation.hazardName === hazard.tempId)
    )
  })
}

// 获取特定危险对应的控制措施
const getControlsForHazard = (hazard: JSAHazard) => {
  if (!formData.value.controlMeasures || !formData.value.hazardControls) return []
  
  return formData.value.controlMeasures.filter(control => {
    return formData.value.hazardControls.some(relation => 
      relation.hazardName === hazard.hazardName && relation.controlMeasureName === control.measureName
    )
  })
}

// 获取工作步骤相关的控制措施（兼容旧函数）
const getStepControls = (stepIndex: number) => {
  const stepHazards = getStepHazards(stepIndex)
  const controls: JSAControlMeasure[] = []
  
  stepHazards.forEach(hazard => {
    const hazardControls = getControlsForHazard(hazard)
    controls.push(...hazardControls)
  })
  
  // 去重
  return controls.filter((control, index, self) => 
    index === self.findIndex(c => c.measureName === control.measureName)
  )
}

// 添加工作步骤
const addStep = () => {
  if (!formData.value.workSteps) {
    formData.value.workSteps = []
  }
  formData.value.workSteps.push({
    stepName: ''
  })
}

// 删除工作步骤
const removeStep = (stepIndex: number) => {
  if (formData.value.workSteps && formData.value.workSteps.length > 1) {
    formData.value.workSteps.splice(stepIndex, 1)
    // 同时移除相关的关联关系
    if (formData.value.workStepHazards) {
      formData.value.workStepHazards = formData.value.workStepHazards.filter(
        rel => rel.workStepSequence !== stepIndex + 1
      )
    }
  }
}

// 添加危险到步骤
const addHazardToStep = (stepIndex: number) => {
  const newHazard = {
    hazardName: ''
  }
  
  if (!formData.value.hazards) {
    formData.value.hazards = []
  }
  formData.value.hazards.push(newHazard)
  
  // 添加关联关系 - 使用hazardName作为唯一标识
  if (!formData.value.workStepHazards) {
    formData.value.workStepHazards = []
  }
  
  // 生成一个临时的唯一标识
  const tempId = `temp_${Date.now()}_${Math.random()}`
  newHazard.tempId = tempId
  
  formData.value.workStepHazards.push({
    workStepSequence: stepIndex + 1,
    hazardName: tempId, // 使用临时ID
    tempId: tempId
  })
}

// 删除危险
const removeHazard = (stepIndex: number, hazardIndex: number) => {
  const stepHazards = getStepHazards(stepIndex)
  const hazard = stepHazards[hazardIndex]
  if (!hazard) return
  
  // 移除危险
  const hazardIndexInAll = formData.value.hazards.findIndex(h => h.hazardName === hazard.hazardName)
  if (hazardIndexInAll !== -1) {
    formData.value.hazards.splice(hazardIndexInAll, 1)
  }
  
  // 移除关联关系
  formData.value.workStepHazards = formData.value.workStepHazards.filter(
    rel => rel.hazardName !== hazard.hazardName
  )
  formData.value.hazardControls = formData.value.hazardControls.filter(
    rel => rel.hazardName !== hazard.hazardName
  )
}

// 为特定危险添加控制措施
const addControlToHazard = (hazard: JSAHazard) => {
  const newControl = {
    measureName: ''
  }
  
  if (!formData.value.controlMeasures) {
    formData.value.controlMeasures = []
  }
  formData.value.controlMeasures.push(newControl)
  
  // 添加关联关系
  if (!formData.value.hazardControls) {
    formData.value.hazardControls = []
  }
  formData.value.hazardControls.push({
    hazardName: hazard.hazardName,
    controlMeasureName: newControl.measureName
  })
}

// 添加控制措施到步骤（兼容旧函数）
const addControlToStep = (stepIndex: number) => {
  const stepHazards = getStepHazards(stepIndex)
  if (stepHazards.length > 0) {
    // 为第一个危险添加控制措施
    addControlToHazard(stepHazards[0])
  }
}

// 删除特定危险的控制措施
const removeControlFromHazard = (hazard: JSAHazard, controlIndex: number) => {
  const hazardControls = getControlsForHazard(hazard)
  const control = hazardControls[controlIndex]
  if (!control) return
  
  // 移除控制措施
  const controlIndexInAll = formData.value.controlMeasures?.findIndex(c => c.measureName === control.measureName)
  if (controlIndexInAll !== undefined && controlIndexInAll !== -1) {
    formData.value.controlMeasures.splice(controlIndexInAll, 1)
  }
  
  // 移除关联关系
  if (formData.value.hazardControls) {
    formData.value.hazardControls = formData.value.hazardControls.filter(
      rel => !(rel.hazardName === hazard.hazardName && rel.controlMeasureName === control.measureName)
    )
  }
}

// 删除控制措施（兼容旧函数）
const removeControl = (stepIndex: number, controlIndex: number) => {
  const stepControls = getStepControls(stepIndex)
  const control = stepControls[controlIndex]
  if (!control) return
  
  // 移除控制措施
  const controlIndexInAll = formData.value.controlMeasures?.findIndex(c => c.measureName === control.measureName)
  if (controlIndexInAll !== undefined && controlIndexInAll !== -1) {
    formData.value.controlMeasures.splice(controlIndexInAll, 1)
  }
  
  // 移除关联关系
  if (formData.value.hazardControls) {
    formData.value.hazardControls = formData.value.hazardControls.filter(
      rel => rel.controlMeasureName !== control.measureName
    )
  }
}
</script>

<style lang="scss" scoped>
.jsa-template-table-form {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  
  .form-header {
    background: #f5f7fa;
    border-bottom: 2px solid #e4e7ed;
    
    .header-row {
      display: grid;
      grid-template-columns: 0.8fr 1fr 1fr;
      min-height: 80px;
      
      .step-header,
      .hazard-header,
      .control-header {
        padding: 16px;
        border-right: 1px solid #e4e7ed;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        
        &:last-child {
          border-right: none;
        }
        
        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
          font-weight: 600;
          color: #303133;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
        
        p {
          margin: 0;
          font-size: 12px;
          color: #606266;
          font-weight: 500;
        }
      }
    }
  }
  
  .form-body {
    .form-row {
      display: grid;
      grid-template-columns: 0.8fr 1fr 1fr;
      border-bottom: 1px solid #e4e7ed;
      
      &:last-child {
        border-bottom: none;
      }
      
      .step-cell,
      .hazard-cell,
      .control-cell {
        padding: 16px;
        border-right: 1px solid #e4e7ed;
        min-height: 200px;
        
        &:last-child {
          border-right: none;
        }
      }
      
      // 工作步骤样式
      .step-cell {
        background: #fafbfc;
        
        .step-number {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          background: #409eff;
          color: white;
          border-radius: 50%;
          font-size: 12px;
          font-weight: 600;
          margin-bottom: 12px;
        }
        
        .step-name-input {
          margin-bottom: 12px;
        }
        
        .step-actions {
          .el-button {
            width: 100%;
          }
        }
      }
      
      // 潜在危险样式
      .hazard-cell {
        .hazard-item {
          display: flex;
          align-items: flex-start;
          margin-bottom: 16px;
          padding: 12px;
          background: #fef5f5;
          border-radius: 6px;
          border: 1px solid #fde2e2;
          
          .hazard-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            background: #f56c6c;
            color: white;
            border-radius: 50%;
            font-size: 11px;
            font-weight: 600;
            margin-right: 8px;
            flex-shrink: 0;
          }
          
          .hazard-content {
            flex: 1;
            
            .hazard-name-input {
              margin-bottom: 8px;
            }
            
            .hazard-actions {
              .el-button {
                width: 100%;
              }
            }
          }
        }
        
        .add-hazard {
          text-align: center;
          margin-top: 8px;
        }
      }
      
      // 控制措施样式
      .control-cell {
        .hazard-control-group {
          margin-bottom: 20px;
          
          .hazard-title {
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e4e7ed;
            
            .hazard-label {
              font-weight: 600;
              color: #606266;
              font-size: 14px;
            }
          }
        }
        
        .control-item {
          display: flex;
          align-items: flex-start;
          margin-bottom: 12px;
          padding: 12px;
          background: #f0f9ff;
          border-radius: 6px;
          border: 1px solid #bae6fd;
          
          .control-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            background: #67c23a;
            color: white;
            border-radius: 50%;
            font-size: 11px;
            font-weight: 600;
            margin-right: 8px;
            flex-shrink: 0;
          }
          
          .control-content {
            flex: 1;
            
            .control-name-input {
              margin-bottom: 8px;
            }
            
            .control-actions {
              .el-button {
                width: 100%;
              }
            }
          }
        }
        
        .add-control-to-hazard {
          text-align: center;
          padding: 8px 0;
          border-top: 1px solid #e4e7ed;
          margin-top: 12px;
        }
        
        .no-hazards {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100px;
          color: #909399;
        }
      }
    }
  }
  
  .form-footer {
    padding: 16px;
    background: #f5f7fa;
    border-top: 1px solid #e4e7ed;
    text-align: center;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .jsa-template-table-form {
    .form-header .header-row,
    .form-body .form-row {
      grid-template-columns: 1fr;
      
      .step-header,
      .hazard-header,
      .control-header,
      .responsible-header,
      .step-cell,
      .hazard-cell,
      .control-cell {
        border-right: none;
        border-bottom: 1px solid #e4e7ed;
        
        &:last-child {
          border-bottom: none;
        }
      }
    }
  }
}
</style>
